<template>
  <div class="coupons-container">
    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="stats-cards" v-loading="loading.stats">
      <el-col :span="6" v-for="(item, index) in statsData" :key="index">
        <el-card shadow="hover" class="stats-card" :body-style="{ padding: '20px' }">
          <div class="stats-card-header">
            <span class="stats-card-title">{{ item.title }}</span>
            <el-tooltip :content="item.tooltip" placement="top">
              <el-icon><QuestionFilled /></el-icon>
            </el-tooltip>
          </div>
          <div class="stats-card-content">
            <span class="stats-card-value">{{ item.value }}</span>
            <span class="stats-card-unit">{{ item.unit }}</span>
            <el-tag :type="item.trend >= 0 ? 'success' : 'danger'" size="small" class="trend-tag">
              {{ item.trend >= 0 ? '+' : '' }}{{ item.trend }}%
            </el-tag>
          </div>
          <div class="stats-card-chart">
            <div ref="trendChartRefs" :id="'trendChart' + index" class="trend-chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 操作栏 -->
    <el-card class="filter-card" shadow="never">
      <el-form :inline="true" :model="filterForm" class="filter-form">
        <el-form-item label="优惠券名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入优惠券名称"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="优惠券类型">
          <el-select v-model="filterForm.type" placeholder="请选择类型" clearable>
            <el-option
              v-for="(label, value) in COUPON_TYPE"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="filterForm.status" placeholder="请选择状态" clearable>
            <el-option
              v-for="(label, value) in COUPON_STATUS"
              :key="value"
              :label="label"
              :value="value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="left">
        <el-button-group>
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            新建优惠券
          </el-button>
          <el-button type="success" @click="handleImport">
            <el-icon><Upload /></el-icon>
            批量导入
          </el-button>
          <el-button type="warning" @click="handleExport">
            <el-icon><Download /></el-icon>
            导出数据
          </el-button>
        </el-button-group>
        <el-button-group>
          <el-button
            v-for="action in quickActions"
            :key="action.value"
            :type="action.type"
            @click="handleQuickAction(action.value)"
          >
            <el-icon><component :is="action.icon" /></el-icon>
            {{ action.label }}
          </el-button>
        </el-button-group>
      </div>
      <div class="right">
        <el-button-group>
          <el-button
            v-for="status in batchActions"
            :key="status.value"
            :type="status.type"
            :disabled="!selectedCoupons.length"
            @click="handleBatchAction(status.value)"
          >
            {{ status.label }}
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 优惠券列表 -->
    <el-card class="list-card" shadow="never" v-loading="loading.list">
      <el-table
        :data="couponList"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="优惠券名称" min-width="200">
          <template #default="scope">
            <div class="coupon-name">
              <el-tag :type="getCouponTypeTag(scope.row.type)" size="small">
                {{ getCouponTypeLabel(scope.row.type) }}
              </el-tag>
              <span>{{ scope.row.name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="value" label="优惠内容" width="180">
          <template #default="scope">
            {{ getCouponValueDisplay(scope.row) }}
          </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="使用门槛" width="120">
          <template #default="scope">
            <span v-if="scope.row.type === COUPON_TYPE.FULL_REDUCTION">
              满{{ scope.row.minAmount }}元可用
            </span>
            <span v-else-if="scope.row.type === COUPON_TYPE.DISCOUNT">
              满{{ scope.row.minAmount }}元可用
            </span>
            <span v-else>无门槛</span>
          </template>
        </el-table-column>
        <el-table-column prop="startTime" label="有效期" width="240">
          <template #default="scope">
            <div class="validity-period">
              <div>{{ scope.row.startTime }} 至 {{ scope.row.endTime }}</div>
              <div class="validity-status" :class="getValidityStatusClass(scope.row)">
                {{ getValidityStatusText(scope.row) }}
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="total" label="发放数量" width="100" align="right" />
        <el-table-column prop="used" label="已使用" width="100" align="right" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button
                v-if="scope.row.status === COUPON_STATUS.APPROVED"
                type="success"
                link
                @click="handleStatusChange(scope.row, COUPON_STATUS.ON)"
              >
                上架
              </el-button>
              <el-button
                v-if="scope.row.status === COUPON_STATUS.ON"
                type="warning"
                link
                @click="handleStatusChange(scope.row, COUPON_STATUS.OFF)"
              >
                下架
              </el-button>
              <el-button
                v-if="[COUPON_STATUS.DRAFT, COUPON_STATUS.REJECTED].includes(scope.row.status)"
                type="primary"
                link
                @click="handleEdit(scope.row)"
              >
                编辑
              </el-button>
              <el-button
                v-if="[COUPON_STATUS.DRAFT, COUPON_STATUS.REJECTED].includes(scope.row.status)"
                type="danger"
                link
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 创建/编辑优惠券对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'create' ? '新建优惠券' : '编辑优惠券'"
      width="800px"
      destroy-on-close
      class="coupon-dialog"
    >
      <el-tabs v-model="activeTab">
        <el-tab-pane label="基本信息" name="basic">
          <el-form
            ref="couponFormRef"
            :model="couponForm"
            :rules="couponRules"
            label-width="100px"
            class="coupon-form"
          >
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="优惠券名称" prop="name">
                  <el-input v-model="couponForm.name" placeholder="请输入优惠券名称" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="优惠券类型" prop="type">
                  <el-select v-model="couponForm.type" placeholder="请选择类型" class="w-full">
                    <el-option
                      v-for="(label, value) in COUPON_TYPE"
                      :key="value"
                      :label="label"
                      :value="value"
                    >
                      <div class="coupon-type-option">
                        <el-tag :type="getCouponTypeTag(value)" size="small">{{ label }}</el-tag>
                        <span class="coupon-type-desc">{{ getCouponTypeDesc(value) }}</span>
                      </div>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item
                  :label="couponForm.type === COUPON_TYPE.DISCOUNT ? '折扣率' : '优惠金额'"
                  prop="value"
                >
                  <el-input-number
                    v-model="couponForm.value"
                    :min="0"
                    :max="couponForm.type === COUPON_TYPE.DISCOUNT ? 10 : 999999"
                    :precision="couponForm.type === COUPON_TYPE.DISCOUNT ? 1 : 2"
                    :step="couponForm.type === COUPON_TYPE.DISCOUNT ? 0.1 : 1"
                    class="w-full"
                  />
                  <span class="unit">
                    {{ couponForm.type === COUPON_TYPE.DISCOUNT ? '折' : '元' }}
                  </span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="使用门槛" prop="minAmount">
                  <el-input-number
                    v-model="couponForm.minAmount"
                    :min="0"
                    :precision="2"
                    :step="10"
                    class="w-full"
                  />
                  <span class="unit">元</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="发放数量" prop="total">
                  <el-input-number
                    v-model="couponForm.total"
                    :min="1"
                    :precision="0"
                    :step="100"
                    class="w-full"
                  />
                  <span class="unit">张</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="每人限领" prop="useLimit">
                  <el-input-number
                    v-model="couponForm.useLimit"
                    :min="1"
                    :precision="0"
                    :step="1"
                    class="w-full"
                  />
                  <span class="unit">张</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="有效期" prop="dateRange">
                  <el-date-picker
                    v-model="couponForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="YYYY-MM-DD"
                    class="w-full"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="领取后有效期" prop="validDays">
                  <el-input-number
                    v-model="couponForm.validDays"
                    :min="1"
                    :precision="0"
                    :step="1"
                    class="w-full"
                  />
                  <span class="unit">天</span>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="使用时间" prop="useTime">
              <el-radio-group v-model="couponForm.useTime">
                <el-radio label="all">全天可用</el-radio>
                <el-radio label="day">仅白天可用 (9:00-18:00)</el-radio>
                <el-radio label="night">仅晚上可用 (18:00-次日9:00)</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="使用范围" prop="useScope">
              <el-radio-group v-model="couponForm.useScope">
                <el-radio label="all">全店可用</el-radio>
                <el-radio label="category">指定分类</el-radio>
                <el-radio label="product">指定商品</el-radio>
              </el-radio-group>
              <div v-if="couponForm.useScope !== 'all'" class="mt-2">
                <el-select
                  v-model="couponForm.scopeIds"
                  multiple
                  filterable
                  :placeholder="couponForm.useScope === 'category' ? '请选择商品分类' : '请选择商品'"
                  class="w-full"
                >
                  <el-option
                    v-for="item in scopeOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-form-item>

            <el-form-item label="用户等级" prop="userLevel">
              <el-radio-group v-model="couponForm.userLevel">
                <el-radio label="all">全部用户</el-radio>
                <el-radio label="level">指定等级</el-radio>
              </el-radio-group>
              <div v-if="couponForm.userLevel === 'level'" class="mt-2">
                <el-select
                  v-model="couponForm.levelIds"
                  multiple
                  filterable
                  placeholder="请选择用户等级"
                  class="w-full"
                >
                  <el-option
                    v-for="item in levelOptions"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </div>
            </el-form-item>

            <el-form-item label="使用说明" prop="description">
              <el-input
                v-model="couponForm.description"
                type="textarea"
                :rows="3"
                placeholder="请输入使用说明"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
        
        <el-tab-pane label="优惠券预览" name="preview">
          <div class="coupon-preview">
            <div class="preview-card" :class="getCouponTypeClass(couponForm.type)">
              <div class="preview-header">
                <el-tag :type="getCouponTypeTag(couponForm.type)" size="small">
                  {{ getCouponTypeLabel(couponForm.type) }}
                </el-tag>
                <span class="preview-name">{{ couponForm.name }}</span>
              </div>
              <div class="preview-content">
                <div class="preview-value">
                  {{ getCouponValueDisplay(couponForm) }}
                </div>
                <div class="preview-condition">
                  {{ getCouponConditionDisplay(couponForm) }}
                </div>
              </div>
              <div class="preview-footer">
                <div class="preview-time">
                  {{ couponForm.dateRange?.[0] }} 至 {{ couponForm.dateRange?.[1] }}
                </div>
                <div class="preview-limit">
                  每人限领{{ couponForm.useLimit }}张
                </div>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading.submit">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 批量导入对话框 -->
    <el-dialog
      v-model="importDialogVisible"
      title="批量导入优惠券"
      width="500px"
      destroy-on-close
    >
      <el-upload
        class="upload-demo"
        drag
        action="/api/merchant/coupons/import"
        :headers="uploadHeaders"
        :on-success="handleImportSuccess"
        :on-error="handleImportError"
        :before-upload="beforeImport"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<el-link type="primary" @click="downloadTemplate">点击上传</el-link>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请上传 Excel 文件，<el-link type="primary" @click="downloadTemplate">下载模板</el-link>
          </div>
        </template>
      </el-upload>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick, watch, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Refresh,
  Plus,
  Download,
  ArrowUp,
  ArrowDown,
  QuestionFilled,
  Upload,
  UploadFilled
} from '@element-plus/icons-vue'
import {
  COUPON_STATUS,
  COUPON_TYPE,
  getCouponList,
  getCouponStats,
  createCoupon,
  updateCoupon,
  deleteCoupon,
  batchDeleteCoupons,
  updateCouponStatus,
  batchUpdateCouponStatus,
  exportCouponData
} from '@/api/coupon'
import * as echarts from 'echarts'

// 统计数据
const loading = reactive({
  stats: false,
  list: false,
  submit: false
})

const statsData = ref([
  {
    title: '优惠券总数',
    value: 0,
    unit: '张',
    trend: '月',
    type: 'primary',
    compare: 0
  },
  {
    title: '已发放数量',
    value: 0,
    unit: '张',
    trend: '月',
    type: 'success',
    compare: 0
  },
  {
    title: '已使用数量',
    value: 0,
    unit: '张',
    trend: '月',
    type: 'warning',
    compare: 0
  },
  {
    title: '优惠总金额',
    value: 0,
    unit: '元',
    trend: '月',
    type: 'danger',
    compare: 0
  }
])

// 筛选表单
const filterForm = reactive({
  name: '',
  type: '',
  status: '',
  dateRange: []
})

// 分页数据
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 优惠券列表
const couponList = ref([])
const selectedCoupons = ref([])

// 批量操作按钮
const batchActions = [
  { label: '批量上架', value: COUPON_STATUS.ON, type: 'success' },
  { label: '批量下架', value: COUPON_STATUS.OFF, type: 'warning' },
  { label: '批量删除', value: 'delete', type: 'danger' }
]

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('create')
const couponFormRef = ref(null)
const couponForm = reactive({
  name: '',
  type: COUPON_TYPE.FULL_REDUCTION,
  value: 0,
  minAmount: 0,
  total: 100,
  dateRange: [],
  description: '',
  useLimit: 1,
  validDays: 7,
  useTime: 'all',
  useScope: 'all',
  scopeIds: [],
  userLevel: 'all',
  levelIds: []
})

// 表单验证规则
const couponRules = {
  name: [
    { required: true, message: '请输入优惠券名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择优惠券类型', trigger: 'change' }
  ],
  value: [
    { required: true, message: '请输入优惠内容', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (couponForm.type === COUPON_TYPE.DISCOUNT && (value < 0 || value > 10)) {
          callback(new Error('折扣率必须在 0-10 之间'))
        } else if (value <= 0) {
          callback(new Error('优惠金额必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  minAmount: [
    { 
      validator: (rule, value, callback) => {
        if (couponForm.type === COUPON_TYPE.FULL_REDUCTION && value <= 0) {
          callback(new Error('满减券门槛必须大于 0'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  total: [
    { required: true, message: '请输入发放数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '发放数量必须大于 0', trigger: 'blur' }
  ],
  dateRange: [
    { required: true, message: '请选择有效期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && value[0] && value[1]) {
          const start = new Date(value[0]).getTime()
          const end = new Date(value[1]).getTime()
          if (start >= end) {
            callback(new Error('结束时间必须大于开始时间'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ],
  description: [
    { required: true, message: '请输入使用说明', trigger: 'blur' },
    { min: 5, max: 200, message: '长度在 5 到 200 个字符', trigger: 'blur' }
  ]
}

// 新增的响应式数据
const activeTab = ref('basic')
const importDialogVisible = ref(false)
const trendChartRefs = ref([])
const scopeOptions = ref([])
const levelOptions = ref([])

// 快捷操作按钮
const quickActions = [
  { label: '优惠券模板', value: 'template', type: 'info', icon: 'Document' },
  { label: '使用记录', value: 'records', type: 'warning', icon: 'List' },
  { label: '数据统计', value: 'stats', type: 'success', icon: 'TrendCharts' }
]

// 获取统计数据
const fetchStats = async () => {
  loading.stats = true
  try {
    const { data } = await getCouponStats()
    statsData.value = [
      {
        title: '优惠券总数',
        value: data.total,
        unit: '张',
        trend: '月',
        type: 'primary',
        compare: data.totalCompare
      },
      {
        title: '已发放数量',
        value: data.issued,
        unit: '张',
        trend: '月',
        type: 'success',
        compare: data.issuedCompare
      },
      {
        title: '已使用数量',
        value: data.used,
        unit: '张',
        trend: '月',
        type: 'warning',
        compare: data.usedCompare
      },
      {
        title: '优惠总金额',
        value: data.amount.toFixed(2),
        unit: '元',
        trend: '月',
        type: 'danger',
        compare: data.amountCompare
      }
    ]
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  } finally {
    loading.stats = false
  }
}

// 获取优惠券列表
const fetchCouponList = async () => {
  loading.list = true
  try {
    const params = {
      page: page.value,
      pageSize: pageSize.value,
      ...filterForm,
      startTime: filterForm.dateRange?.[0],
      endTime: filterForm.dateRange?.[1]
    }
    const { data } = await getCouponList(params)
    couponList.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取优惠券列表失败:', error)
    ElMessage.error('获取优惠券列表失败')
  } finally {
    loading.list = false
  }
}

// 搜索
const handleSearch = () => {
  page.value = 1
  fetchCouponList()
}

// 重置
const handleReset = () => {
  Object.keys(filterForm).forEach(key => {
    filterForm[key] = ''
  })
  filterForm.dateRange = []
  handleSearch()
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchCouponList()
}

const handleCurrentChange = (val) => {
  page.value = val
  fetchCouponList()
}

// 选择变化
const handleSelectionChange = (selection) => {
  selectedCoupons.value = selection
}

// 新建优惠券
const handleCreate = () => {
  dialogType.value = 'create'
  Object.keys(couponForm).forEach(key => {
    couponForm[key] = key === 'type' ? COUPON_TYPE.FULL_REDUCTION : ''
  })
  dialogVisible.value = true
}

// 编辑优惠券
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(couponForm).forEach(key => {
    if (key === 'dateRange') {
      couponForm[key] = [row.startTime, row.endTime]
    } else {
      couponForm[key] = row[key]
    }
  })
  dialogVisible.value = true
}

// 删除优惠券
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除该优惠券吗？', '提示', {
      type: 'warning'
    })
    await deleteCoupon(row.id)
    ElMessage.success('删除成功')
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除优惠券失败:', error)
      ElMessage.error('删除优惠券失败')
    }
  }
}

// 批量操作
const handleBatchAction = async (action) => {
  if (!selectedCoupons.value.length) {
    return ElMessage.warning('请选择要操作的优惠券')
  }

  const ids = selectedCoupons.value.map(item => item.id)
  try {
    if (action === 'delete') {
      await ElMessageBox.confirm('确定要删除选中的优惠券吗？', '提示', {
        type: 'warning'
      })
      await batchDeleteCoupons(ids)
      ElMessage.success('批量删除成功')
    } else {
      await batchUpdateCouponStatus(ids, action)
      ElMessage.success('批量操作成功')
    }
    fetchCouponList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量操作失败:', error)
      ElMessage.error('批量操作失败')
    }
  }
}

// 状态变更
const handleStatusChange = async (row, status) => {
  try {
    await updateCouponStatus(row.id, status)
    ElMessage.success('操作成功')
    fetchCouponList()
  } catch (error) {
    console.error('状态变更失败:', error)
    ElMessage.error('状态变更失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!couponFormRef.value) return
  
  try {
    await couponFormRef.value.validate()
    loading.submit = true
    
    const [startTime, endTime] = couponForm.dateRange
    const data = {
      ...couponForm,
      startTime,
      endTime
    }
    delete data.dateRange
    
    if (dialogType.value === 'create') {
      await createCoupon(data)
      ElMessage.success('创建成功')
    } else {
      await updateCoupon(data.id, data)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    fetchCouponList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    loading.submit = false
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const params = {
      ...filterForm,
      startTime: filterForm.dateRange?.[0],
      endTime: filterForm.dateRange?.[1]
    }
    const res = await exportCouponData(params)
    
    // 创建下载链接
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = `优惠券数据_${new Date().getTime()}.xlsx`
    link.click()
    window.URL.revokeObjectURL(link.href)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 获取状态标签
const getStatusLabel = (status) => {
  return COUPON_STATUS[status] || status
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    [COUPON_STATUS.DRAFT]: 'info',
    [COUPON_STATUS.PENDING]: 'warning',
    [COUPON_STATUS.APPROVED]: 'success',
    [COUPON_STATUS.REJECTED]: 'danger',
    [COUPON_STATUS.NOT_STARTED]: 'info',
    [COUPON_STATUS.ONGOING]: 'success',
    [COUPON_STATUS.FINISHED]: 'warning',
    [COUPON_STATUS.INVALID]: 'danger',
    [COUPON_STATUS.ON]: 'success',
    [COUPON_STATUS.OFF]: 'info'
  }
  return typeMap[status] || 'info'
}

// 获取优惠券类型标签
const getCouponTypeLabel = (type) => {
  return COUPON_TYPE[type] || type
}

// 获取优惠券类型标签样式
const getCouponTypeTag = (type) => {
  const typeMap = {
    [COUPON_TYPE.NEW_USER]: 'success',
    [COUPON_TYPE.FULL_REDUCTION]: 'danger',
    [COUPON_TYPE.DIRECT_REDUCTION]: 'warning',
    [COUPON_TYPE.PRODUCT]: 'primary',
    [COUPON_TYPE.SHOP]: 'info',
    [COUPON_TYPE.REPURCHASE]: 'success',
    [COUPON_TYPE.FANS]: 'warning',
    [COUPON_TYPE.DISCOUNT]: 'danger',
    [COUPON_TYPE.FREE_SHIPPING]: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取优惠内容显示
const getCouponValueDisplay = (row) => {
  switch (row.type) {
    case COUPON_TYPE.FULL_REDUCTION:
      return `满${row.minAmount}减${row.value}元`
    case COUPON_TYPE.DIRECT_REDUCTION:
      return `立减${row.value}元`
    case COUPON_TYPE.DISCOUNT:
      return `${row.value}折`
    case COUPON_TYPE.FREE_SHIPPING:
      return '免运费'
    case COUPON_TYPE.NEW_USER:
      return `新人专享${row.value}元`
    case COUPON_TYPE.PRODUCT:
      return `商品优惠${row.value}元`
    case COUPON_TYPE.SHOP:
      return `店铺优惠${row.value}元`
    case COUPON_TYPE.REPURCHASE:
      return `复购专享${row.value}元`
    case COUPON_TYPE.FANS:
      return `涨粉专享${row.value}元`
    default:
      return `${row.value}元`
  }
}

// 添加有效期状态判断
const getValidityStatusText = (row) => {
  const now = new Date().getTime()
  const start = new Date(row.startTime).getTime()
  const end = new Date(row.endTime).getTime()
  
  if (now < start) {
    return '未开始'
  } else if (now > end) {
    return '已结束'
  } else {
    return '进行中'
  }
}

const getValidityStatusClass = (row) => {
  const now = new Date().getTime()
  const start = new Date(row.startTime).getTime()
  const end = new Date(row.endTime).getTime()
  
  if (now < start) {
    return 'not-started'
  } else if (now > end) {
    return 'finished'
  } else {
    return 'ongoing'
  }
}

// 获取优惠券类型描述
const getCouponTypeDesc = (type) => {
  const descMap = {
    [COUPON_TYPE.NEW_USER]: '新用户首次下单可用',
    [COUPON_TYPE.FULL_REDUCTION]: '订单满指定金额可用',
    [COUPON_TYPE.DIRECT_REDUCTION]: '无门槛直接减免',
    [COUPON_TYPE.PRODUCT]: '指定商品可用',
    [COUPON_TYPE.SHOP]: '全店商品可用',
    [COUPON_TYPE.REPURCHASE]: '复购用户专享',
    [COUPON_TYPE.FANS]: '关注店铺粉丝专享',
    [COUPON_TYPE.DISCOUNT]: '订单折扣优惠',
    [COUPON_TYPE.FREE_SHIPPING]: '免运费优惠'
  }
  return descMap[type] || ''
}

// 获取优惠券条件显示
const getCouponConditionDisplay = (form) => {
  const conditions = []
  
  if (form.minAmount > 0) {
    conditions.push(`满${form.minAmount}元可用`)
  }
  
  if (form.useTime !== 'all') {
    conditions.push(form.useTime === 'day' ? '仅白天可用' : '仅晚上可用')
  }
  
  if (form.useScope !== 'all') {
    conditions.push(form.useScope === 'category' ? '指定分类可用' : '指定商品可用')
  }
  
  if (form.userLevel === 'level') {
    conditions.push('指定等级可用')
  }
  
  return conditions.join('，') || '无使用限制'
}

// 获取优惠券预览样式类
const getCouponTypeClass = (type) => {
  const classMap = {
    [COUPON_TYPE.NEW_USER]: 'new-user',
    [COUPON_TYPE.FULL_REDUCTION]: 'full-reduction',
    [COUPON_TYPE.DIRECT_REDUCTION]: 'direct-reduction',
    [COUPON_TYPE.PRODUCT]: 'product',
    [COUPON_TYPE.SHOP]: 'shop',
    [COUPON_TYPE.REPURCHASE]: 'repurchase',
    [COUPON_TYPE.FANS]: 'fans',
    [COUPON_TYPE.DISCOUNT]: 'discount',
    [COUPON_TYPE.FREE_SHIPPING]: 'free-shipping'
  }
  return classMap[type] || ''
}

// 初始化趋势图表
const initTrendCharts = () => {
  trendChartRefs.value.forEach((el, index) => {
    if (!el) return
    
    const chart = echarts.init(el)
    const option = {
      grid: {
        top: 0,
        right: 0,
        bottom: 0,
        left: 0
      },
      xAxis: {
        type: 'category',
        show: false,
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        show: false
      },
      series: [{
        data: statsData.value[index].trendData,
        type: 'line',
        smooth: true,
        symbol: 'none',
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: statsData.value[index].trend >= 0 ? '#67C23A' : '#F56C6C' },
            { offset: 1, color: 'rgba(255, 255, 255, 0.1)' }
          ])
        },
        lineStyle: {
          color: statsData.value[index].trend >= 0 ? '#67C23A' : '#F56C6C'
        }
      }]
    }
    chart.setOption(option)
  })
}

// 处理快捷操作
const handleQuickAction = (action) => {
  switch (action) {
    case 'template':
      // 跳转到优惠券模板页面
      break
    case 'records':
      // 跳转到使用记录页面
      break
    case 'stats':
      // 跳转到数据统计页面
      break
  }
}

// 处理批量导入
const handleImport = () => {
  importDialogVisible.value = true
}

// 下载导入模板
const downloadTemplate = () => {
  // 实现下载模板逻辑
}

// 上传前校验
const beforeImport = (file) => {
  const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                 file.type === 'application/vnd.ms-excel'
  if (!isExcel) {
    ElMessage.error('只能上传 Excel 文件！')
    return false
  }
  return true
}

// 上传成功回调
const handleImportSuccess = (response) => {
  ElMessage.success('导入成功')
  importDialogVisible.value = false
  fetchCouponList()
}

// 上传失败回调
const handleImportError = () => {
  ElMessage.error('导入失败')
}

// 监听表单变化，更新预览
watch(
  () => ({ ...couponForm }),
  () => {
    if (activeTab.value === 'preview') {
      // 可以在这里添加预览更新逻辑
    }
  },
  { deep: true }
)

// 组件挂载时初始化
onMounted(() => {
  fetchStats()
  fetchCouponList()
  // 获取分类和等级选项
  // fetchScopeOptions()
  // fetchLevelOptions()
  nextTick(() => {
    initTrendCharts()
  })
})

// 组件卸载时销毁图表
onUnmounted(() => {
  trendChartRefs.value.forEach(chart => {
    chart && chart.dispose()
  })
})
</script>

<style scoped>
.coupons-container {
  padding: 20px;
}

.stats-cards {
  margin-bottom: 20px;
}

.stats-card {
  height: 120px;
}

.stats-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.stats-card-title {
  font-size: 14px;
  color: #909399;
}

.stats-card-content {
  margin-bottom: 12px;
}

.stats-card-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.stats-card-unit {
  font-size: 14px;
  color: #909399;
  margin-left: 4px;
}

.stats-card-footer {
  font-size: 12px;
  color: #909399;
}

.compare-value {
  margin-left: 4px;
  font-weight: 500;
}

.compare-value.up {
  color: #67C23A;
}

.compare-value.down {
  color: #F56C6C;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.list-card {
  margin-bottom: 20px;
}

.coupon-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.unit {
  margin-left: 8px;
  color: #909399;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 0;
}

:deep(.el-input-number) {
  width: 180px;
}

:deep(.el-date-editor) {
  width: 240px;
}

.validity-period {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.validity-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  display: inline-block;
  width: fit-content;
}

.validity-status.not-started {
  background-color: #e6f7ff;
  color: #1890ff;
}

.validity-status.ongoing {
  background-color: #f6ffed;
  color: #52c41a;
}

.validity-status.finished {
  background-color: #fff7e6;
  color: #fa8c16;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 22px;
  font-size: 12px;
}

:deep(.el-tag--success) {
  background-color: #f0f9eb;
  border-color: #e1f3d8;
  color: #67c23a;
}

:deep(.el-tag--warning) {
  background-color: #fdf6ec;
  border-color: #faecd8;
  color: #e6a23c;
}

:deep(.el-tag--danger) {
  background-color: #fef0f0;
  border-color: #fde2e2;
  color: #f56c6c;
}

:deep(.el-tag--info) {
  background-color: #f4f4f5;
  border-color: #e9e9eb;
  color: #909399;
}

:deep(.el-tag--primary) {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  color: #409eff;
}

.coupon-dialog {
  :deep(.el-dialog__body) {
    padding: 20px 30px;
  }
}

.coupon-form {
  .w-full {
    width: 100%;
  }
  
  .mt-2 {
    margin-top: 8px;
  }
}

.coupon-type-option {
  display: flex;
  align-items: center;
  gap: 8px;
  
  .coupon-type-desc {
    color: #909399;
    font-size: 12px;
  }
}

.coupon-preview {
  display: flex;
  justify-content: center;
  padding: 20px;
  
  .preview-card {
    width: 300px;
    padding: 20px;
    border-radius: 8px;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    
    &.new-user {
      background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
    }
    
    &.full-reduction {
      background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
    }
    
    &.direct-reduction {
      background: linear-gradient(135deg, #E6A23C 0%, #F3B760 100%);
    }
    
    &.product {
      background: linear-gradient(135deg, #409EFF 0%, #79BBFF 100%);
    }
    
    &.shop {
      background: linear-gradient(135deg, #909399 0%, #C0C4CC 100%);
    }
    
    &.repurchase {
      background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
    }
    
    &.fans {
      background: linear-gradient(135deg, #E6A23C 0%, #F3B760 100%);
    }
    
    &.discount {
      background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
    }
    
    &.free-shipping {
      background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
    }
    
    .preview-header {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;
      
      .preview-name {
        color: #fff;
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .preview-content {
      text-align: center;
      margin-bottom: 16px;
      
      .preview-value {
        color: #fff;
        font-size: 24px;
        font-weight: 600;
        margin-bottom: 8px;
      }
      
      .preview-condition {
        color: rgba(255, 255, 255, 0.8);
        font-size: 14px;
      }
    }
    
    .preview-footer {
      display: flex;
      justify-content: space-between;
      color: rgba(255, 255, 255, 0.8);
      font-size: 12px;
    }
  }
}

.trend-chart {
  height: 50px;
  margin-top: 8px;
}

.stats-card {
  .trend-tag {
    margin-left: 8px;
  }
  
  .stats-card-chart {
    margin-top: 12px;
  }
}

.upload-demo {
  :deep(.el-upload-dragger) {
    width: 100%;
  }
  
  .el-upload__tip {
    margin-top: 12px;
    text-align: center;
  }
}

/* 响应式布局优化 */
@media screen and (max-width: 1400px) {
  .el-col-6 {
    width: 50%;
    margin-bottom: 20px;
  }
}

@media screen and (max-width: 768px) {
  .el-col-6 {
    width: 100%;
  }
  
  .toolbar {
    flex-direction: column;
    gap: 16px;
    
    .left, .right {
      width: 100%;
      justify-content: center;
    }
  }
  
  .coupon-dialog {
    :deep(.el-dialog) {
      width: 95% !important;
      margin: 0 auto;
    }
  }
}
</style>
